#include <16f1824.h>

#device ICD=TRUE

#FUSES NOWDT                 	//No Watch Dog Timer
#FUSES INTRC_IO              	//Internal RC Osc, no CLKOUT
#FUSES WDT_SW                
#FUSES NOPUT                 	//No Power Up Timer
#FUSES MCLR                  	//Master Clear pin enabled
#FUSES NOPROTECT             	//Code not protected from reading
#FUSES CPD                 		//No EE protection
#FUSES NOBROWNOUT            	//No brownout reset
#FUSES NOCLKOUT              
#FUSES IESO                  	//Internal External Switch Over mode enabled
#FUSES FCMEN                 	//Fail-safe clock monitor enabled
#FUSES NOWRT                 	//Program memory not write protected
#FUSES PLL                   
#FUSES STVREN                	//Stack full/underflow will cause reset
#FUSES BORV19                
#FUSES DEBUG               		//Debug mode for ICD
#FUSES NOLVP                 	//No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O

#USE delay(clock=8000000)
#USE spi(MASTER, FORCE_HW, BITS=16, BAUD=1600)

#define INTCON      0x00B
#define load		PIN_C3

long trama;
int direccion,datos,codigo_ir=0,contador_TMR0=0;

#int_EXT
void  EXT_isr(void) 
{
	clear_interrupt(INT_TIMER0);
	set_timer0(210);
	enable_interrupts(INT_TIMER0);
	disable_interrupts(INT_EXT);
}

#int_TIMER2
void  TIMER2_isr(void) 
{
	output_low(load);
	spi_xfer(trama);
	output_high(load);
}

#int_TIMER0
void  TIMER0_isr(void) 
{
	int i;
	contador_TMR0++;

	if(contador_TMR0==7)
		{
		contador_TMR0=0;
		disable_interrupts(INT_TIMER0);

		for(i=6;i>0;i--)
			{
			if(input(PIN_A2))
				bit_set(codigo_IR,i-1);
			else
				bit_clear(codigo_IR,i-1);

			delay_us(1778);
			}

		enable_interrupts(INT_EXT);
		clear_interrupt(INT_EXT);
		clear_interrupt(INT_TIMER0);
		}
		else
			break;

}

//*************************** PROGRAMA PRINCIPAL *********************************

void main(void)
{

	clear_interrupt(INT_EXT);

   	ext_int_edge(L_TO_H);
	enable_interrupts(INT_EXT);
	enable_interrupts(INT_TIMER2);
  	enable_interrupts(GLOBAL);

	setup_timer_0(RTCC_INTERNAL|RTCC_DIV_16|RTCC_8_bit);		//2.0 ms overflow
	setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);		//32.7 ms overflow
	setup_timer_2(T2_DIV_BY_16,78,16);		//632 us overflow, 10.1 ms interrupt

	while(TRUE)
	{
	switch(codigo_ir)
		{
		case 0x00: 	trama=0x0000;
					break;
		case 0x01: 	trama=0x0001;
					break;
		case 0x02:	trama=0x0002;
					break;
		case 0x20:	trama=0x0020;
					break;
		}
	}


}